//
//  CommunityMainCollectionCell.m
//  ArtDog
//
//  Created by dllo on 16/9/3.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CommunityMainCollectionCell.h"
#import "CommunityMainHeadView.h"
#import "BaseTableView.h"
#import "HLMacro.h"
#import "ZWYNetTool.h"
#import "NSString+Common.h"
#import "CommunityTopicTableCell.h"
#import "MJRefresh.h"
#import "MJRefreshComponent+RefreshStyle.h"

// Model
#import "CommunityMainModel.h"
#import "CommunityAdvList.h"
#import "CommunityListUsers.h"
#import "CommunityTopicList.h"
#import "CommunityMainCellContentController.h"
#import "CommunityMainViewController.h"

@interface CommunityMainCollectionCell ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet BaseTableView *tableView;

@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic, strong) NSMutableArray<CommunityMainModel *> *mainModelArray;
@property (nonatomic, strong) NSMutableArray<NSMutableArray<CommunityTopicList *> *> *loadArray;

@property (nonatomic, assign) BOOL isOpen;

@end

@implementation CommunityMainCollectionCell

- (void)awakeFromNib {
    [super awakeFromNib];
    _isOpen = NO;
    if (_mainModelArray == nil) {
        CommunityMainModel *model = [[CommunityMainModel alloc]init];
        _mainModelArray = [NSMutableArray arrayWithObjects:model, model, model, nil];
    }
    if (_loadArray == nil) {
        NSMutableArray *topicList = [NSMutableArray array];
        _loadArray = [NSMutableArray arrayWithObjects:topicList, topicList, topicList, nil];
    }
    [self setupBasic];
}

- (void)setupBasic
{
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)setType:(NSInteger)type
{
    _type = type;
    [_tableView reloadData];
    if (_tableView.mj_header == nil) {
        [self refreshTableView];
    }
    if (_mainModelArray[type].topicList == nil && _mainModelArray[type].hotTopicList == nil) {
        [self handleData];
    }
    if (_loadArray[type].count == 0) {
        if (type == 0) {
            if (_mainModelArray[type].hotTopicList != nil) {
                _loadArray[type] = _mainModelArray[type].hotTopicList.mutableCopy;
            }
        } else {
            if (_mainModelArray[type].topicList != nil) {
                _loadArray[type] = _mainModelArray[type].topicList.mutableCopy;
            }
        }
    }
    [_tableView registerNib:[UINib nibWithNibName:@"CommunityTopicTableCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"communityTopicTableCell"];
}

#pragma mark - 数据请求
- (void)handleData
{
    _pageIndex = 1;
    NSString *urlString = [self getUrlString];
    [ZWYNetTool GET:urlString andBody:nil andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _mainModelArray[_type] = [CommunityMainModel modelWithDic:result[@"data"]];
        if (_type == 0) {
            CommunityMainViewController *vc = (CommunityMainViewController *)self.superview.superview.nextResponder;
            vc.isHaveActivity = NO;
            if (_mainModelArray[_type].hotTopicList != nil) {
                _loadArray[_type] = _mainModelArray[_type].hotTopicList.mutableCopy;
            }
        } else {
            if (_mainModelArray[_type].topicList != nil) {
                _loadArray[_type] = _mainModelArray[_type].topicList.mutableCopy;
            }
        }
        [_tableView.mj_header endRefreshing];
        [_tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        [_tableView.mj_header endRefreshing];
        CommunityMainViewController *vc = (CommunityMainViewController *)self.superview.superview.nextResponder;
        vc.isHaveActivity = NO;
        NSLog(@"%@", error);
    }];
}

- (void)handleLoadData
{
    NSString *urlString = [self getUrlString];
    [ZWYNetTool GET:urlString andBody:nil andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
        CommunityMainModel *mainModel = [CommunityMainModel modelWithDic:result[@"data"]];
        if (_type == 0) {
            for (CommunityTopicList *topicModel in mainModel.hotTopicList) {
                [_loadArray[_type] addObject:topicModel];
            }
        } else {
            for (CommunityTopicList *topicModel in mainModel.topicList) {
                [_loadArray[_type] addObject:topicModel];
            }
        }
        [_tableView.mj_footer endRefreshing];
        [_tableView reloadData];
        
    } andFailureBlock:^(NSError *error) {
        [_tableView.mj_footer endRefreshing];
        NSLog(@"%@", error);
    }];
}

- (NSString *)getUrlString
{
    NSString *urlString;
    if (_type == 0) {
        urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"discovery/v4/communityHotRecommand"] andParams:@{@"pageIndex": [NSString stringWithFormat:@"%ld", _pageIndex], @"token": [NSString getUserDefaultToken], @"type": [NSString stringWithFormat:@"%ld", _type]}];
    } else if (_type == 1) {
        urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"discovery/v4/communityLatest"] andParams:@{@"pageIndex": [NSString stringWithFormat:@"%ld", _pageIndex], @"token": [NSString getUserDefaultToken], @"type": [NSString stringWithFormat:@"%ld", _type]}];
    } else {
        urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"discovery/v4/communityWatch"] andParams:@{@"pageIndex": [NSString stringWithFormat:@"%ld", _pageIndex], @"token": [NSString getUserDefaultToken], @"userId": [NSString getUserDefaultId]}];
    }
    return urlString;
}

#pragma mark - tableView 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_type == 0) {
        return 2;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_type == 0) {
        if (section == 0) {
            return 0;
        }
    }
    return _loadArray[_type].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommunityTopicTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"communityTopicTableCell"];
    cell.topicModel = _loadArray[_type][indexPath.item];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellHeight = [CommunityTopicTableCell getCellHeight];
    return cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_type == 0 && section == 0) {
        return SCREEN_WIDTH / 2 + 140;
    } else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CommunityMainHeadView *headerView = [[CommunityMainHeadView alloc]init];
    if (_mainModelArray[_type].advList != nil) {
        headerView.advList = _mainModelArray[_type].advList;
        headerView.listUsers = _mainModelArray[_type].listUsers;
    }
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommunityMainCellContentController *cellContentVC = [[CommunityMainCellContentController alloc]init];
    cellContentVC.topicModel = _loadArray[_type][indexPath.row];
    UIView *view;
    while (1) {
        if ([view.nextResponder isKindOfClass:[UIViewController class]]) {
            break;
        } else {
            if (view == nil) {
                view = (UIView *)self.nextResponder;
            } else {
                view = (UIView *)view.nextResponder;
            }
        }
    }
    UIViewController *vc = (UIViewController *)view.nextResponder;
    [vc.navigationController pushViewController:cellContentVC animated:YES];
}

#pragma mark - 刷新
- (void)refreshTableView
{
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self handleData];
    }];
    [_tableView.mj_header mjRefreshStateHeaderStyle];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _pageIndex = _loadArray[_type].count / 10 + 1;
        [self handleLoadData];
    }];
    [_tableView.mj_footer mjRefreshAutoStateFooterStyle];
}


@end
